package com.xindaoapp.happypet.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.RecommendCicleData;
import com.xindaoapp.happypet.bean.RecommendCicleData.RecommendCicle;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.LoginManager;
import com.xindaoapp.happypet.view.FixGridLayout;

/**
 * 主页_最新
 * 
 * @author Stone
 */
public class CopyOfMainFragment_New extends BaseFragment implements OnClickListener {

    public CopyOfMainFragment_New() {
        super();
    }

    private boolean mIsLoaded;
    private TextView tv_title;
    private ImageView iv_left, iv_right, iv_jiantou, iv_point1, iv_point2, iv_point3, iv_mypoint;
    /** 切换tab */
    private ViewPager viewPager;
    private PopupWindow mPopupWindow1, mPopupWindow2;
    private List<RecommendCicleData.RecommendCicle> mCicles1, mCicles2;
    private FixGridLayout layout_changyong, layout_huodong;
    private RelativeLayout lay_scroll;
    private DrawerLayout mDrawerLayout;
    private ImageView iv_closepop, iv_refresh;
    private HasNewReceiver mHasNewReceiver;
    private Animation operatingAnim;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.fragment_main_new, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initViews() {
        super.initViews();

        mHasNewReceiver = new HasNewReceiver();
        mContext.registerReceiver(mHasNewReceiver, new IntentFilter(Constants.ACTION_HASNEW));

        mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        Fragment[] fragments =
                new Fragment[] {ZuiXinFragment.newInstance(true),
                        ZuiXinFragment.newInstance(false), BeautifulFragment.newInstance()};

        String[] titles = new String[] {"最新", "好友", "美图"};
        String[] hasRights = new String[] {"1", "1", "1"};


        tv_title = (TextView) mView.findViewById(R.id.tv_title);
        iv_left = (ImageView) mView.findViewById(R.id.iv_left);
        iv_right = (ImageView) mView.findViewById(R.id.iv_right);
        iv_jiantou = (ImageView) mView.findViewById(R.id.iv_jiantou);
        iv_mypoint = (ImageView) mView.findViewById(R.id.iv_mypoint);
        viewPager = (ViewPager) mView.findViewById(R.id.viewpager);

        initPop1();
        initPop2();

        MainViewPagerAdapter adapter =
                new MainViewPagerAdapter(getChildFragmentManager(), fragments, titles, hasRights);

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setOnPageChangeListener(adapter);

        new LoginManager(getActivity()).autoLogin();
    }


    @Override
    protected void initEvents() {
        super.initEvents();
        tv_title.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        iv_right.setOnClickListener(this);
        iv_jiantou.setOnClickListener(this);
        iv_mypoint.setOnClickListener(this);
    }

    @Override
    protected void loadDatas() {
        super.loadDatas();
        getData();
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        mContext.unregisterReceiver(mHasNewReceiver);
    }

    private void getData() {
        // TODO Auto-generated method stub

        HappyPetApplication.get().getMoccaApi()
                .getRecommendCicleData(new IRequest<RecommendCicleData>() {

                    @Override
                    public void request(RecommendCicleData t) {



                        if (t == null) {

                        } else {

                            if (operatingAnim != null) {
                                iv_refresh.clearAnimation();
                            }

                            mIsLoaded = true;
                            if (!(t.array1.size() == 0)) {
                                // 适配上
                                mCicles1 = t.array1;
                                // gridView.setAdapter(new QuanziAdapter());
                                bindData(true);
                            }
                            if (!(t.array2.size() == 0)) {
                                // 适配上
                                mCicles2 = t.array2;
                                // gridView.setAdapter(new QuanziAdapter());
                                bindData(false);
                            }
                        }
                    }

                    private void bindData(final boolean isNormal) {

                        if (isNormal) {
                            layout_changyong.removeAllViews();
                        } else {
                            layout_huodong.removeAllViews();
                        }

                        final List<RecommendCicle> cicles;
                        cicles = isNormal ? mCicles1 : mCicles2;
                        for (int i = 0; i < cicles.size(); i++) {
                            final int j = i;
                            View view =
                                    LayoutInflater.from(mContext).inflate(R.layout.item_quanzi,
                                            null);
                            TextView tView = (TextView) view.findViewById(R.id.tv_quanzi);
                            tView.setText(cicles.get(i).tagname);
                            tView.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    // TODO 跳转到标签帖子列表
                                    mPopupWindow2.dismiss();

                                    Intent intent = new Intent(mContext, MyTagListActivity.class);
                                    intent.putExtra(Constants.KEY_GROUP_NAME, cicles.get(j).tagname);
                                    intent.putExtra(Constants.KEY_TAGID, cicles.get(j).tagid);
                                    startActivity(intent);

                                }
                            });
                            if (isNormal) {
                                layout_changyong.addView(view);
                            } else {
                                layout_huodong.addView(view);
                            }
                        }


                    }
                });


    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.tv_title:
            case R.id.iv_jiantou:
            case R.id.iv_mypoint:
                iv_mypoint.setVisibility(View.GONE);
                // 弹出pop
                iv_jiantou.setVisibility(View.VISIBLE);
                iv_jiantou.setImageResource(R.drawable.zhankai_c);
                mPopupWindow1.showAsDropDown(tv_title,
                        tv_title.getWidth() / 2 - CommonUtil.dip2px(mContext, 60),
                        // 保证尺寸是根据屏幕像素密度来的
                        0);

                // mPopupWindow1.showAtLocation(mView.findViewById(R.id.top_bar), Gravity.TOP
                // | Gravity.LEFT,
                // CommonParameter.sScreenWidth / 2 - CommonUtil.dip2px(mContext, 60),
                // CommonUtil.dip2px(mContext, 70));
                // CommonUtil.dip2px(mContext, 55));

                break;
            case R.id.iv_left:
                // 预留
                mDrawerLayout.openDrawer(Gravity.LEFT);

                break;
            case R.id.iv_right:
                // 根据所在tab,进行弹出pop
                // if (mIsLoaded) {
                // } else {
                // getData();
                // }
                mPopupWindow2.showAtLocation(mView, Gravity.CENTER, 0, 0);
                break;


            default:
                break;
        }

    }

    private void initPop2() {

        // TODO Auto-generated method stub
        LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
        /* 设置显示menu布局 view子VIEW */
        View sub_view = mLayoutInflater.inflate(R.layout.item_pop2, null);

        iv_closepop = (ImageView) sub_view.findViewById(R.id.iv_closepop);
        layout_changyong = (FixGridLayout) sub_view.findViewById(R.id.lay_changyong);
        layout_huodong = (FixGridLayout) sub_view.findViewById(R.id.lay_huodong);
        lay_scroll = (RelativeLayout) sub_view.findViewById(R.id.lay_scroll);
        iv_refresh = (ImageView) sub_view.findViewById(R.id.iv_refresh);

        RelativeLayout.LayoutParams layoutParams =
                (android.widget.RelativeLayout.LayoutParams) lay_scroll.getLayoutParams();
        layoutParams.width = LayoutParams.MATCH_PARENT;
        layoutParams.height = CommonParameter.sScreenHeight / 2;
        lay_scroll.setLayoutParams(layoutParams);

        layout_changyong.removeAllViewsInLayout();
        layout_huodong.removeAllViewsInLayout();

        /* 第一个参数弹出显示view 后两个是窗口大小 */
        mPopupWindow2 =
                new PopupWindow(sub_view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        /* 设置背景显示 */
        mPopupWindow2.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        /* 设置系统动画 */
        mPopupWindow2.setAnimationStyle(R.style.Pop_Custom);
        // mPopupWindow2.setAnimationStyle(android.R.style.Animation_Dialog);
        /* 设置点击menu以外其他地方以及返回键退出 */
        mPopupWindow2.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow2.setOutsideTouchable(true);
        sub_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow2.dismiss();
            }
        });

        iv_closepop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow2.dismiss();
            }
        });

        operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotateanimation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);


        // animation =
        // new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f,
        // Animation.RELATIVE_TO_SELF, 0.5f);
        // animation.setFillAfter(false);
        // animation.setRepeatCount(0);// 设置重复次数
        // animation.setDuration(200);
        // LinearInterpolator lin = new LinearInterpolator();
        // animation.setInterpolator(lin);
        // iv_refresh.setAnimation(animation);
        iv_refresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (operatingAnim != null) {
                    iv_refresh.startAnimation(operatingAnim);
                }
                getData();
            }
        });

        mPopupWindow2.update();


    }

    @SuppressLint("NewApi")
    private void initPop1() {
        // TODO Auto-generated method stub
        LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
        View view = mLayoutInflater.inflate(R.layout.popmenu1, null);

        iv_point1 = (ImageView) view.findViewById(R.id.iv_point1);
        iv_point2 = (ImageView) view.findViewById(R.id.iv_point2);
        iv_point3 = (ImageView) view.findViewById(R.id.iv_point3);

        // view.getBackground().setAlpha(100);
        mPopupWindow1 = new PopupWindow(view, CommonUtil.dip2px(mContext, 120), // 这里宽度需要自己指定，使用
                // WRAP_CONTENT
                // 会很大
                CommonUtil.dip2px(mContext, 150), true);

        // 要求11
        if (Build.VERSION.SDK_INT >= 11) {
            mPopupWindow1.getContentView().setAlpha(0.9F);
        }

        view.findViewById(R.id.iv_jingxuan).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow1.dismiss();
                iv_point2.setVisibility(View.GONE);
                viewPager.setCurrentItem(1);
            }
        });
        view.findViewById(R.id.iv_zuixin).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow1.dismiss();
                viewPager.setCurrentItem(0);

            }
        });
        view.findViewById(R.id.iv_meitu).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow1.dismiss();
                iv_point3.setVisibility(View.GONE);
                viewPager.setCurrentItem(2);

            }
        });



        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        // // 设置FilterPopupWindow弹出窗体的背景
        mPopupWindow1.setBackgroundDrawable(dw);
        // popupWindow.setBackgroundDrawable();
        // 使其聚集
        mPopupWindow1.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow1.setOutsideTouchable(true);
        mPopupWindow1.setAnimationStyle(R.style.PopupDownAnimation);

        // popupWindow.showAtLocation(mView, Gravity.CENTER_HORIZONTAL,
        // CommonParameter.sScreenWidth / 2, CommonUtil.dip2px(mContext, 55));
        mPopupWindow1.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                iv_jiantou.setImageResource(R.drawable.zhankai_n);
            }
        });
        mPopupWindow1.update();

    }

    /**
     * tab切换适配器
     * 
     * @author Stone
     * 
     */
    public class MainViewPagerAdapter extends FragmentPagerAdapter implements OnPageChangeListener {
        Fragment[] fragments;
        String[] tabTitles;
        String[] hasRights;

        public MainViewPagerAdapter(FragmentManager fm, Fragment[] fragments, String[] tabTitles,
                String[] hasRights) {
            super(fm);
            this.fragments = fragments;
            this.tabTitles = tabTitles;
            this.hasRights = hasRights;
            setTabSelected(0);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments[arg0];
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {}

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageSelected(int position) {
            setTabSelected(position);
        }

        private void setTabSelected(int position) {

            tv_title.setText(tabTitles[position]);

            if (hasRights[position].equals("1")) {
                iv_right.setVisibility(View.VISIBLE);
            } else {
                iv_right.setVisibility(View.GONE);
            }

        }
    }


    class HasNewReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // iv_point1
            // .setVisibility(Integer.parseInt(intent.getStringExtra("zuixin")) > 0 ? View.VISIBLE
            // : View.GONE);
            iv_point2
                    .setVisibility(Integer.parseInt(intent.getStringExtra("friend")) > 0 ? View.VISIBLE
                            : View.GONE);
            iv_point3
                    .setVisibility(Integer.parseInt(intent.getStringExtra("meitu")) > 0 ? View.VISIBLE
                            : View.GONE);

            if (iv_point2.getVisibility() == View.VISIBLE
                    || iv_point3.getVisibility() == View.VISIBLE) {
                iv_mypoint.setVisibility(View.VISIBLE);
                iv_jiantou.setVisibility(View.GONE);
            }
        }


    }



    /**
     * 圈子适配器
     * 
     * @author Stone
     * 
     */
    // public class QuanziAdapter extends BaseAdapter {
    //
    //
    // @Override
    // public int getCount() {
    // return mCicles.size();
    // }
    //
    // @Override
    // public View getView(final int position, View convertView, ViewGroup parent) {
    // ViewHolder holder;
    // if (convertView == null) {
    // holder = new ViewHolder();
    // convertView = View.inflate(mContext, R.layout.item_quanzi, null);
    // holder.tv_quanzi = (TextView) convertView.findViewById(R.id.tv_quanzi);
    // convertView.setTag(holder);
    // } else {
    // holder = (ViewHolder) convertView.getTag();
    // }
    //
    //
    // holder.tv_quanzi.setText(mCicles.get(position).tagname);
    // return convertView;
    // }
    //
    // @Override
    // public Object getItem(int position) {
    // return null;
    // }
    //
    // @Override
    // public long getItemId(int position) {
    // return position;
    // }
    //
    // class ViewHolder {
    // TextView tv_quanzi;
    // }
    // }

}
